package com.yuexiang.melodyhub.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.List;

public class JwtUtil {

    private static final String SECRET_KEY = "KA8zv^nMkIZ#7Wg^tTVz$2EAFhmsFjvS";
    private static final SecretKey SECRET_KEY_INSTANCE = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
    private static final long EXPIRATION = 60 * 60 * 1000;

    public static String generateToken(String username, List<String> authorities) {
        return Jwts.builder()
                .subject(username)
                .claim("roles", authorities)
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SECRET_KEY_INSTANCE)
                .compact();
    }

    public static Jws<Claims> parseToken(String token) {
        return Jwts.parser()
                .verifyWith(SECRET_KEY_INSTANCE)
                .build()
                .parseSignedClaims(token);
    }

    public static boolean isTokenValid(String token) {
        try {
            parseToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getUsername(String token) {
        try {
            return parseToken(token).getPayload().getSubject();
        } catch (Exception e) {
            return null;
        }
    }

    public static List<String> getAuthorities(String token) {
        try {
            return parseToken(token).getPayload().get("roles", List.class);
        } catch (Exception e) {
            return null;
        }
    }

    public static String refreshToken(String token) {
        try {
            Jws<Claims> claimsJws = parseToken(token);
            Claims claims = claimsJws.getPayload();
            return generateToken(claims.getSubject(), claims.get("roles", List.class));
        } catch (Exception e) {
            return null;
        }
    }

}
